package com.itheima.controller;


import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.constant.MessageConstant;
import com.itheima.entity.Result;
import com.itheima.service.MemberService;
import com.itheima.service.ReportService;
import com.itheima.service.SetmealService;
import net.sf.jasperreports.engine.*;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 图形数据展示的控制层
 */
@RestController
@RequestMapping("/report")
public class ReportController {

    @Reference
    private MemberService memberService;

    @Reference
    private SetmealService setmealService;

    @Reference
    private ReportService reportService;

    /**
     * 会员数量折线图
     * @return
     */
    @GetMapping("/getMemberReport")
    public Result getMemberReport(){
        try {
            Map<String, Object> map = new HashMap<>();
            ArrayList<String> months = new ArrayList<>();
            Calendar calendar=Calendar.getInstance();
            calendar.add(Calendar.MONTH,-13);
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
            for (int i = 0; i < 12; i++) {
                calendar.add(Calendar.MONTH,1);
                String date = sdf.format(calendar.getTime());
                months.add(date);
            }
            ArrayList<Integer> memberCount = memberService.selectMemberCountByMonth(months);
            map.put("months",months);
            map.put("memberCount",memberCount);
            return Result.success(MessageConstant.GET_MEMBER_NUMBER_REPORT_SUCCESS,map);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.failed(MessageConstant.GET_MEMBER_NUMBER_REPORT_FAIL);
        }
    }


    /**
     * 套餐预约占比饼形图
     * @return
     */
    @GetMapping("/getSetmealReport")
    public Result getSetmealReport(){
        try {
            HashMap<String, Object> map = new HashMap<>();
            ArrayList<String> setmealNames=new ArrayList<>();
            List<Map<String,Object>> setmealCount = setmealService.findSetmealOrderCount();
            for (Map<String, Object> setmealMap : setmealCount) {
                String name = (String) setmealMap.get("name");
                setmealNames.add(name);
            }
            map.put("setmealNames",setmealNames);
            map.put("setmealCount",setmealCount);
            return Result.success(MessageConstant.GET_SETMEAL_COUNT_REPORT_SUCCESS,map);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.failed(MessageConstant.GET_SETMEAL_COUNT_REPORT_FAIL);
        }
    }

    /**
     * 运营数据统计
     * @return
     */
    @GetMapping("/getBusinessReportData")
    public Result getBusinessReportData(){
        try {
            Map<String, Object> businessReport = reportService.getBusinessReport();
            return Result.success(MessageConstant.GET_BUSINESS_REPORT_SUCCESS,businessReport);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.failed(MessageConstant.GET_BUSINESS_REPORT_FAIL);
        }
    }

    /**
     * 导出运营数据报表(Excel)
     * @return
     */
    @RequestMapping("/exportBusinessReport")
    public Result exportBusinessReport(HttpServletRequest request, HttpServletResponse response){
        try {
            Map<String, Object> result = reportService.getBusinessReport();
            String reportDate = (String) result.get("reportDate");
            Integer todayNewMember = (Integer) result.get("todayNewMember");
            Integer totalMember = (Integer) result.get("totalMember");
            Integer thisWeekNewMember = (Integer) result.get("thisWeekNewMember");
            Integer thisMonthNewMember = (Integer) result.get("thisMonthNewMember");
            Integer todayOrderNumber = (Integer) result.get("todayOrderNumber");
            Integer todayVisitsNumber = (Integer) result.get("todayVisitsNumber");
            Integer thisWeekOrderNumber = (Integer) result.get("thisWeekOrderNumber");
            Integer thisWeekVisitsNumber = (Integer) result.get("thisWeekVisitsNumber");
            Integer thisMonthOrderNumber = (Integer) result.get("thisMonthOrderNumber");
            Integer thisMonthVisitsNumber = (Integer) result.get("thisMonthVisitsNumber");
            List<Map> hotSetmeal = (List<Map>) result.get("hotSetmeal");
            String templatePath = request.getSession().getServletContext().getRealPath("template") + File.separator + "report_template.xlsx";
            XSSFWorkbook workbook = new XSSFWorkbook(new FileInputStream(new File(templatePath)));
            XSSFSheet sheet = workbook.getSheetAt(0);
            sheet.getRow(2).getCell(5).setCellValue(reportDate);
            XSSFRow row = sheet.getRow(4);
            row.getCell(5).setCellValue(todayNewMember);
            row.getCell(7).setCellValue(totalMember);

            XSSFRow row1 = sheet.getRow(5);
            row1.getCell(5).setCellValue(thisWeekNewMember);
            row1.getCell(7).setCellValue(thisMonthNewMember);

            XSSFRow row2 = sheet.getRow(7);
            row2.getCell(5).setCellValue(todayOrderNumber);
            row2.getCell(7).setCellValue(todayVisitsNumber);

            XSSFRow row3 = sheet.getRow(8);
            row3.getCell(5).setCellValue(thisWeekOrderNumber);
            row3.getCell(7).setCellValue(thisWeekVisitsNumber);

            XSSFRow row4 = sheet.getRow(9);
            row4.getCell(5).setCellValue(thisMonthOrderNumber);
            row4.getCell(7).setCellValue(thisMonthVisitsNumber);

            int rowNum=12;
            for (Map map : hotSetmeal) {
                String name = (String) map.get("name");
                Integer setmeal_count = (Integer) map.get("setmeal_count");
                BigDecimal proportion = (BigDecimal) map.get("proportion");
                XSSFRow row5 = sheet.getRow(rowNum);
                row5.getCell(4).setCellValue(name);
                row5.getCell(5).setCellValue(setmeal_count);
                row5.getCell(6).setCellValue(proportion.doubleValue());
                rowNum++;
            }
            ServletOutputStream outputStream = response.getOutputStream();
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setHeader("content-Disposition","attachment;fileName=report.xlsx");
            workbook.write(outputStream);
            outputStream.flush();
            outputStream.close();
            workbook.close();
            return null;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 导出运营数据报表(PDF)
     * @return
     */
    @RequestMapping("/exportBusinessReport4PDF")
    public Result exportBusinessReport4PDF(HttpServletRequest request,HttpServletResponse response){
        try {
            Map<String, Object> report = reportService.getBusinessReport();
            List<Map> hotSetmeal = (List<Map>) report.get("hotSetmeal");
            String jrxmlPath=request.getSession().getServletContext().getRealPath("template")+File.separator+"health_business3.jrxml";
            String jasperPath=request.getSession().getServletContext().getRealPath("template")+File.separator+"health_business3.jasper";
            JasperCompileManager.compileReportToFile(jrxmlPath,jasperPath);
            JasperPrint jasperPrint = JasperFillManager.fillReport(jasperPath, report, new JRBeanCollectionDataSource(hotSetmeal));
            ServletOutputStream outputStream = response.getOutputStream();
            response.setContentType("application/pdf");
            response.setHeader("content-Disposition","attachment;fileName=repot.pdf");
            JasperExportManager.exportReportToPdfStream(jasperPrint,outputStream);
            outputStream.flush();
            outputStream.close();
            return null;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}
